package com.tnsw.noxnox.streamer;

import com.tnsw.noxnox.db.DBManager;
import com.tnsw.noxnox.lab.SimulateGCM;
import com.tnsw.noxnox.settopbox.STBWebserver;

import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.http.THttpBase;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class StreamerService extends IntentService {

	private int port = 7779;
	private static StreamerService sInstance;
	private String tag = "StreamerService";
	private AsyncManager asyncManager;
	private DBManager dbm;
	
	private MediaHTTPServer webserver;
	
	public StreamerService() {
		super("");
		this.initialize();
	}
	
	public StreamerService(String name) {
		super(name);
		this.initialize();
	}
	
	private void initialize() {
		this.asyncManager = AsyncManager.getInstance();
		this.dbm = DBManager.getInstance(this);
		
		SimulateGCM.getInstance(this);
		
		sInstance = this;
	}
	
	public static StreamerService getInstance() {
		return(sInstance);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(tag, "onStartCommand(flags=" + flags + ", startId=" + startId + ")");
		
		try {
			this.webserver = new MediaHTTPServer(this, this.port);	
			this.webserver.startThread();
			
		} catch (Exception e) {
			Log.e(tag, "onStartCommand - " + e.toString(), e);
			this.asyncManager.appendNetworkLog("onStartCommand - " + e.toString());
		}
		
		return(START_STICKY);
	}
	
	public String getMediaPlayUrl(int primaryKey) {
		String url = "";
		String wifiIP = THttpBase.getWiFiIPAddress(this);
		
		if (wifiIP.equals("0.0.0.0")) {
			url = "http://localhost:" + String.valueOf(this.port) + "/";
		} else {
			url = "http://" + wifiIP + ":" + String.valueOf(this.port) + "/";
		}
		
		url = url + "media/play?id=" + String.valueOf(primaryKey);
		
		return(url);
	}

}
